package test.org.jdk.test1;

import org.junit.Test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by lcx on 2017/6/2.
 */
public class BeanFactory {

    @Test
    public void test(){
        UserDAO userDAO = BeanFactory.getBean();
        userDAO.save();
        userDAO.update();
    }

    public static UserDAO getBean(){
        //准备目标
        final UserDAO userDAO = new UserDAOImpl();
        //切面类
        final Aspect aspect = new Aspect();
        //代理类

        return (UserDAO) Proxy.newProxyInstance(
                BeanFactory.class.getClassLoader(), new Class[]{UserDAO.class},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        aspect.Before();

                        Object object = method.invoke(userDAO,args);

                        aspect.After();

                        return object;
                    }
                }
        );
    }
}
